
#include "ini_config_manager.h"

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

// 设置指定的 ini 文件
void IniConfigManager::setIniFile(const std::string& filePath) {
    this->filePath = filePath;
    loadConfig();
}

// 从文件加载配置
void IniConfigManager::loadConfig() {
    std::ifstream file(filePath);
    if (!file.is_open()) {
        return;
    }

    std::string currentGroup;
    std::string line;
    while (std::getline(file, line)) {
        // 去除首尾空格
        line.erase(0, line.find_first_not_of(" \t"));
        line.erase(line.find_last_not_of(" \t") + 1);

        if (line.empty() || line[0] == ';') {
            continue;
        }

        if (line[0] == '[' && line.back() == ']') {
            currentGroup = line.substr(1, line.length() - 2);
        } else {
            size_t pos = line.find('=');
            if (pos != std::string::npos) {
                std::string key = line.substr(0, pos);
                std::string value = line.substr(pos + 1);
                configMap[currentGroup][key] = value;
            }
        }
    }
    file.close();
}

// 将配置保存到文件
void IniConfigManager::saveConfig() {
    std::lock_guard<std::mutex> lock(mtx);  // 加锁
    std::ofstream file(filePath);
    if (!file.is_open()) {
        return;
    }

    for (const auto& groupPair : configMap) {
        const std::string& group = groupPair.first;
        const auto& keyValueMap = groupPair.second;

        file << "[" << group << "]" << std::endl;
        for (const auto& kvPair : keyValueMap) {
            const std::string& key = kvPair.first;
            const std::string& value = kvPair.second;
            file << key << "=" << value << std::endl;
        }
        file << std::endl;
    }
    file.close();
}

// 新增指定 group 指定 key 配置项
void IniConfigManager::addConfig(const std::string& key, const std::string& value, const std::string& group) {
    // std::lock_guard<std::mutex> lock(mtx);  // 加锁
    configMap[group][key] = value;
    saveConfig();
}

// 读取指定 group 的配置值
std::string IniConfigManager::getConfig(const std::string& key, const std::string& group) {
    auto groupIt = configMap.find(group);
    if (groupIt != configMap.end()) {
        auto keyIt = groupIt->second.find(key);
        if (keyIt != groupIt->second.end()) {
            return keyIt->second;
        }
    }
    return "";
}

// 删除指定 group 下的指定配置项
void IniConfigManager::deleteConfig(const std::string& key, const std::string& group) {
    // std::lock_guard<std::mutex> lock(mtx);  // 加锁
    auto groupIt = configMap.find(group);
    if (groupIt != configMap.end()) {
        auto keyIt = groupIt->second.find(key);
        if (keyIt != groupIt->second.end()) {
            groupIt->second.erase(keyIt);
            saveConfig();
        }
    }
}